package com.xtsoft.platform.base.system.controller;

import com.fasterxml.jackson.databind.JsonMappingException;

import com.xtsoft.core.controller.GenericController;
import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.utils.HeaderUtil;
import com.xtsoft.core.utils.StringUtils;
import com.xtsoft.platform.base.system.domain.SysRegion;
import com.xtsoft.platform.base.system.domain.SysUser;
import com.xtsoft.platform.base.system.service.SysRegionService;
import com.xtsoft.platform.globe.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.List;
import java.util.Optional;
/**
 * @ClassName:  SysRegion 
 * @Author author
 * @Vesion 1.0
 * Create Time:
 * <p><b>Class Description:</b>[TODO]<p>
 * REST controller for managing sysRegion.
 */
@Tag(name = "机构记录--处理接口")
@RestController
public class SysRegionController extends GenericController {
	
	private final Logger log = LoggerFactory.getLogger(SysRegionController.class);
	
	@Autowired	
	private SysRegionService sysRegionService;
	
    /**
     * 功能：新增一个实体，POST请求  
     * 
     * 路径：  /sysRegion/add
     *
     * @param sysRegion 要新增的实体
     * @return ResponseEntity, json格式,http status 201 表示成功 , html body中包含 sysRegion
     * 若sysRegion存在主键值, 则http status 400 (Bad Request)
     * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
     */
	
	@Parameter(name = "sysRegion", description = "机构记录", required = false)
	@Operation(summary  = "新增机构记录")
    @PostMapping("/sysRegion/add")
   
    public ResponseEntity<SysRegion> add(@RequestBody SysRegion sysRegion) throws URISyntaxException {
        log.debug("REST request 保存 : SysRegion", sysRegion);
        SysUser user=(SysUser) SecurityUtils.getLoginedUser();
        if (!StringUtils.isEmpty(sysRegion.getRegUniqueId())) {
        	log.info("新增一条机构记录失败", user.getLoginId(), user.getUsername(), getClientIp());
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("sysRegion", "idexists", "A new sysRegion cannot already have an ID")).body(null);
        }
        SysRegion result = sysRegionService.save(sysRegion);
        log.info("成功新增一条机构记录", user.getLoginId(), user.getUsername(), getClientIp());
        return ResponseEntity.created(new URI("/sysRegion/get/" + result.getRegUniqueId()))
            .headers(HeaderUtil.createEntityCreationAlert("sysRegion", result.getRegUniqueId().toString()))
            .body(result);
    }	

    /**
     * 功能：更新一个实体，PUT请求  
     * 
     * 路径：  /sysRegion/update
     *
     * @param sysRegion 要更新的 sysRegion
     * @return ResponseEntity, json格式, http status 200 表示成功 , html body中包含 sysRegion,
     * 如果sysRegion无效，则http status 404  (Bad Request)
     * 如果sysRegion不能更新，则http status 500 (Internal Server Error)
     * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
     */
	
	

	@Parameter(name = "sysRegion", description = "机构记录", required = false)
	@Operation(summary  = "更新机构记录")
    @PostMapping("/sysRegion/update")

    public ResponseEntity<SysRegion> update(@RequestBody SysRegion sysRegion) throws URISyntaxException {
        log.debug("REST request 更新： SysRegion", sysRegion);
        SysUser user=(SysUser) SecurityUtils.getLoginedUser();
        if (sysRegion.getRegUniqueId() == null) {
        	log.info("修改一条机构记录失败", user.getLoginId(), user.getUsername(), getClientIp());
            return add(sysRegion);
        }
        SysRegion result = sysRegionService.save(sysRegion);
        log.info("成功修改一条机构记录", user.getLoginId(), user.getUsername(), getClientIp());
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("sysRegion", sysRegion.getRegUniqueId().toString()))
            .body(result);
    }  

    /**
     * 功能：获取分页的实体集合，GET请求  
     * 
     * 路径：  /sysRegion/getAll
     *
     * @param pageable,页码信息
     * @return the ResponseEntity, json格式，  http status 200 表示成功  , html body中包含 SysRegion的 list集合
     * @throws URISyntaxException 如果出错，则产生页码信息的 HTTP headers
     * @throws ParseException 
     * @throws IOException 
     * @throws JsonMappingException 
     * @throws JsonParseException 
     */
    
    @Parameter(name = "pageable",description = "分页",required = false)
	@Operation(summary  = "根据分页获取机构记录并按照Id升序排序")
    @GetMapping("/sysRegion/getAll")   
    public ResponseEntity<QueryResult<SysRegion>> getAll(Pageable pageable)
        throws URISyntaxException, ParseException, JsonParseException, JsonMappingException, IOException {
        log.debug("REST request 获取页：SysRegion");
        QueryFilter<SysRegion> filter =new QueryFilter<SysRegion>(SysRegion.class);
        filter.addFilterFromRequest(request);
        filter.addSort("regionId", com.xtsoft.core.repository.Sort.ASC);
        QueryResult<SysRegion> result=sysRegionService.anyQuery(filter);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 功能：根据主键值获取一个实体对象，GET请求
     *
     * 路径： /sysRegion/get/:id
     *
     * @param id 实体主键值
     * @return  ResponseEntity, json格式, http status 200 表示成功 , html body中包含 SysRegion, http status 404 表示未找到
     */
    

	@Parameter(name = "sysRegion", description = "机构记录", required = false)
	@Operation(summary  = "新增机构记录")
    @GetMapping("/sysRegion/get/{id}")
  
    public ResponseEntity<SysRegion> get(@PathVariable String id) {
        log.debug("REST request 获取： SysRegion", id);
        SysRegion sysRegion = sysRegionService.get(id);
        return Optional.ofNullable(sysRegion)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    } 

    /**
     * 功能：根据主键值删除一个实体对象，DELETE请求
     *
     * 路径： /sysRegion/delete/:id
     *
     * @param  id 实体主键值
     * @return ResponseEntity,json格式, http status 200 (OK)
     */
	
	@Parameter(name = "id", description = "id", required = false)
	@Operation(summary  = "删除机构记录")
    @GetMapping("/sysRegion/delete/{id}") 
    public ResponseEntity<Void> delete(@PathVariable String id) {
        log.debug("REST request 删除： SysRegion", id);
        SysUser user=(SysUser) SecurityUtils.getLoginedUser();
		sysRegionService.remove(id);
		log.info("成功删除一条机构记录", user.getLoginId(), user.getUsername(), getClientIp());
    	
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("sysRegion", id)).build();
    }
    
    
    /**
     * 功能：构建资源树
     * 
     * 路径：/sysResource/getResourceTree
     */
	
	
	@Operation(summary  = "根据当前用户Id获取记录树")
    @GetMapping("/sysRegion/getRegionTree")
    public ResponseEntity<String> getRegionTree(){
    	String currentuserId="";
		return new ResponseEntity<>(sysRegionService.getRegionTree(currentuserId),HttpStatus.OK);
    }
    
    /**
     * 功能：获取
     * 
     * 路径：/sysRegion/getCounty
     */
	
	@Parameter(name = "id", description = "id", required = false)
	@Operation(summary  = "根据id获取机构记录总数")
    @GetMapping("/sysRegion/getCounty/{id}")
    public ResponseEntity<List<SysRegion>> getCounty(@PathVariable String id){
    	List<SysRegion> list=sysRegionService.findByPreRegionId(id);
		return new ResponseEntity<>(list,HttpStatus.OK);
    }
}
